package com.mnkjxy.beauty.net.protocal;

import java.io.StringWriter;
import java.util.List;

import org.xmlpull.v1.XmlSerializer;

import android.util.Xml;

public class Message {
	private Header header = new Header();
	private Body body = new Body();
	private String userName;

	/**
	 * 序列化整个xml文件
	 * 
	 * @param serializer
	 */
	public void serializerMessage(XmlSerializer serializer) {
		try {
			serializer.startTag(null, "message");
			// 设置请求的用户名
			header.getUsername().setTagValue(userName);

			header.serializerHeader(serializer,body.getWholeBody());

			serializer.startTag(null, "body");
			serializer.text(body.getBodyInnerDESInfo());
			serializer.endTag(null, "body");

			serializer.endTag(null, "message");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * @param element
	 */
	public String getXml(BaseElement element) {
		if (element == null) {
			throw new IllegalArgumentException("请求不能为空");
		}
		// 设置用户名和请求类型
		this.userName = element.getUserName();
		String transactiontype = element.getTransactiontype();
		header.getTransactiontype().setTagValue(transactiontype);
		// 设置element里面的内容
		List<BaseElement> elementsList = body.getElements();

		elementsList.add(element);

		// 开始序列化整个xml文档
		XmlSerializer serializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();
		try {
			serializer.setOutput(writer);
			serializer.startDocument("utf-8", true);
			this.serializerMessage(serializer);
			serializer.endDocument();

			return writer.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}
}
